import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
	state: {
		goodsInCart: []
	},
	mutations: {
		addToCart(state, goodInfo) {
			state.goodsInCart.push(goodInfo)
		},
		clearCart(state) {
			state.goodsInCart = []
		},
		plusCount(state, goodId) {
			state.goodsInCart.forEach(good => {
				good.goodId === goodId && good.count++
			})
		},
		minusCount(state, goodId) {
			let index = 0,
				zero = 1

			state.goodsInCart.forEach(good => {
				if (good.goodId === goodId) {
					zero = --good.count
				}

				zero && index++
			})

			!zero && state.goodsInCart.splice(index, 1)
		}
	},
  getters: {
    totalCount(state) {
      return state.goodsInCart.reduce((prev, item) => prev + item.count, 0)
    }
  }
})
